package com.yc.vote.servlet;

import com.yc.common.bean.Result;
import com.yc.common.biz.BizException;
import com.yc.common.servlet.BaseServlet;
import com.yc.vote.entity.User;
import com.yc.vote.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserServiceImpl biz = new UserServiceImpl();
    public Result login(HttpServletRequest request, HttpServletResponse response){
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        try{
            User user = biz.login(uname,pwd);
            request.getSession().setAttribute("loginedUser", user);
            return Result.success("登录成功！", null);
        } catch (BizException e){
            e.printStackTrace();
            return Result.failure(e.getMessage(), null);
        }
    }

    public User getLoginedUser(HttpServletRequest request, HttpServletResponse response){
        Object o = request.getSession().getAttribute("loginedUser");
        User loginedUser = (User) o;
        if (loginedUser != null){
            // 移除私密信息
            loginedUser.setPwd(null);
            return loginedUser;
        } else {
            return null;
        }
    }
   /** 该方法不是 ajax 方法，到 axios.get ... **/
   public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
       // 销毁会话
       request.getSession().invalidate();
       response.sendRedirect("../index.html");
   }
}
